<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\common\service\message\order;

use app\api\model\OrderGoods as OrderGoodsModel;
use app\api\model\user\SendMessage as SendMessageModel;
use app\common\enum\order\refund\RefundStatus as RefundStatusEnum;
use app\common\enum\order\refund\RefundType as RefundTypeEnum;
use app\common\library\wechat\WxBase;
use app\common\library\helper;
use app\common\model\WxnoticeTemplate;
use app\common\model\UserOauth;
use app\common\model\UserOauth as UserOauthModel;
use app\store\model\Express as ExpressModel;
use app\store\model\Supplier as SupplierModel;
use app\common\model\Order as OrderModel;
use app\common\enum\order\refund\AuditStatus as AuditStatusEnum;
use app\store\model\Goods as GoodsModel;


/**
 * 消息通知服务 [订单通知]
 * Class Delivery
 * @package app\common\service\message\order
 */
class WxOrderMessage extends WxBase
{
    // 微信支付配置
    private $config;

    // 当前商城ID
    private $storeId;

    /**
     * 构造函数
     * @param array $config
     * @param int|null $storeId
     */
    public function __construct(array $config = [], ?int $storeId = null)
    {
        parent::__construct();
        $this->config  = $config;
        $this->storeId = $storeId;
        if (!empty($this->config)) {
            $this->setConfig($this->config['app_id'], $this->config['app_secret']);
        }
    }

    //发货通知
    public function WxMessageDelivery(array $param)
    {
        $goodName = [];
        if ($param['order']['goods']) {
            foreach ($param['order']['goods'] as $key => $value) {
                $goodName[] = $value['goods_name'] . ' x ' . $value['total_num'];
            }
        }
        $goodName = implode(',', $goodName);
        $goodName = helper::truncateString($goodName, 20);
        if (empty($goodName)) {
            return false;
        }
        $token = $this->getAccessToken();
        if (!$token) {
            throwError('微信配置有误');
        }

        //获取快递公司
        if ($param['order']['express_id']) {
            $model   = new ExpressModel;
            $express = $model->detail($param['order']['express_id']);
        }

        $openId = UserOauthModel::getMpWeiXinOpenId($param['order']['user_id']);

        $supplierModel = new SupplierModel;
        $supplierList  = $supplierModel->getListByCategory()->toArray();//所有供应商
        $supplierList  = array_column($supplierList, 'business_name', 'supplier_id');
        //$supplier_name = $supplierList[$param['order']['supplier_id']] ?? '邦邦电商';
        $supplier_name = '邦豆百货';
        $express_name  = $express['express_name'] ?? '';
        $wx_template   = WxnoticeTemplate::wxMessageTemplate(['delivery'])['delivery'];//发货通知

        if ($wx_template['store_id'] == '10002') {//服装商城
            $formwork = '{
             "touser": "' . $openId . '",
             "template_id": "' . $wx_template['template_id'] . '",
             "page":"pages/order/detail?orderId=' . $param['order']['order_id'] . '",
             "data": {
                 "character_string1": {
                     "value": "' . $param['order']['order_no'] . '"
                 },
                 "thing2": {
                     "value":"' . $goodName . '"
                 },
                 "thing7": {
                    "value": "' . $express_name . '"
                },
                "character_string4": {
                    "value": "' . $param['order']['express_no'] . '"
                },
                "date5": {
                    "value": "' . date('Y-m-d H:i:s') . '"
                }
            }
        }';
        } else {
            $formwork = '{
             "touser": "' . $openId . '",
             "template_id": "' . $wx_template['template_id'] . '",
             "page":"pages/order/detail?orderId=' . $param['order']['order_id'] . '",
             "data": {
                 "character_string1": {
                     "value": "' . $param['order']['order_no'] . '"
                 },
                 "thing2": {
                     "value":"' . $supplier_name . '"
                 },
                 "thing3": {
                    "value": "' . $goodName . '"
                },
                "thing4": {
                    "value": "' . $express_name . '"
                },
                "character_string5": {
                    "value": "' . $param['order']['express_no'] . '"
                }
            }
        }';
        }


        $url    = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token . "";
        $result = helper::httpRequest($url, $formwork);
        log_record($result);
        /*$result = json_decode($result, true);
        if ($result['errcode'] != 0) {//微信消息发送失败
            $sendMessageModel = new SendMessageModel();
            $data['status']   = 0;
            $data['update_time'] = time();
            $sendMessageModel->where(['user_id' => $param['order']['user_id'], 'type' => 'delivery'])->update($data);
        }*/
    }

    //虚拟商品充值成功通知
    public function VirtualGoodMessageNotice(array $param)
    {
        if (!isset($param['order_id'])) {
            return false;
        }
        $model    = new OrderGoodsModel;
        $goodInfo = $model->where('order_id', '=', $param['order_id'])->find();
        $goodName = helper::truncateString($goodInfo['goods_name'], 20);
        if (empty($goodName)) {
            return false;
        }
        $token = $this->getAccessToken();
        if (!$token) {
            throwError('微信配置有误');
        }

        $openId = UserOauthModel::getMpWeiXinOpenId($param['user_id']);

        $formwork = '{
             "touser": "' . $openId . '",
             "template_id": "EUnv6mAhemFkCgrUtlEGf17MXESDnuHuOk71FMdnBiw",
             "page":"pages/order/detail?orderId=' . $param['order_id'] . '",
             "data": {
                 "character_string1": {
                     "value": "' . $param['order_no'] . '"
                 },
                 "short_thing2": {
                    "value": "会员充值"
                },
                "amount3": {
                    "value": "' . $goodInfo['total_pay_price'] . '"
                },
                "time4": {
                    "value": "' . $param['complete_time'] . '"
                }
            }
        }';
        $url      = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token . "";
        $result   = helper::httpRequest($url, $formwork);
        log_record($result);
    }

    /*//虚拟商品充值失败、订单取消通知
    public function OrderGoodFailMessageNotice(array $param)
    {
        if (!isset($param['order_id'])) {
            return false;
        }
        if (isset($param['order_goods_id'])) {
            $filter['order_goods_id'] = $param['order_goods_id'];
        }
        $filter['order_id'] = $param['order_id'];
        $model              = new OrderGoodsModel;
        $goodsInfo          = $model->where($filter)->select()->toArray();
        if(empty($goodsInfo)){
            return false;
        }
        $total_pay_price = 0;
        foreach ($goodsInfo as $key => $value) {
            $goodName[] = $value['goods_name'] . ' x ' . $value['total_num'];
            $total_pay_price += $value['total_pay_price'];
        }
        $goodName = implode(',', $goodName);
        $goodName = helper::truncateString($goodName, 20);
        if (empty($goodName)) {
            return false;
        }
        $token = $this->getAccessToken();
        if (!$token) {
            throwError('微信配置有误');
        }
        if(isset($param['pay_price'])){
            $pay_price = $param['pay_price'];
        }else{
            $pay_price = $total_pay_price;
        }

        if(empty($param['message'])){
            return false;
        }
        $openId      = UserOauthModel::getMpWeiXinOpenId($param['user_id']);
        $wx_template = WxnoticeTemplate::wxMessageTemplate('virtual_good_fail');//订单取消通知
        if ($wx_template['store_id'] == '10002') {//服装商城
            $formwork = '{
             "touser": "' . $openId . '",
             "template_id": "' . $wx_template['template_id'] . '",
             "page":"pages/order/detail?orderId=' . $param['order_id'] . '",
             "data": {
                 "character_string1": {
                     "value": "' . $param['order_no'] . '"
                 },
                 "thing2": {
                    "value": "' . $goodName . '"
                },
                "amount3": {
                    "value": "' . $pay_price . '"
                },
                "time4": {
                    "value": "' . date('Y-m-d H:i:s') . '"
                },
                "thing5": {
                    "value": "' . $param['message'] . '"
                }
            }
        }';
        } else {
            $formwork = '{
             "touser": "' . $openId . '",
             "template_id": "' . $wx_template['template_id'] . '",
             "page":"pages/order/detail?orderId=' . $param['order_id'] . '",
             "data": {
                 "character_string1": {
                     "value": "' . $param['order_no'] . '"
                 },
                 "thing2": {
                    "value": "' . $goodName . '"
                },
                "amount3": {
                    "value": "' . $pay_price . '"
                },
                "time4": {
                    "value": "' . date('Y-m-d H:i:s') . '"
                },
                "thing5": {
                    "value": "' . $param['message'] . '"
                }
            }
        }';
        }
        $url    = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token . "";
        $result = helper::httpRequest($url, $formwork);
        log_record($result);
    }*/

    //售后订单状态更新通知
    public function WxMessageOrderSaleService(array $param)
    {
        if(isset($param['goods_name'])){
            $goodName = $param['goods_name'];
        }else{
            //获取售后商品信息
            $model    = new OrderGoodsModel;
            $goodInfo = $model->where('order_id', '=', $param['order_id'])
                ->where('order_goods_id', '=', $param['order_goods_id'])->find();
            $goodName = helper::truncateString($goodInfo['goods_name'], 20);
        }
        if (empty($goodName)) {
            return false;
        }
        $token = $this->getAccessToken();
        if (!$token) {
            throwError('微信配置有误');
        }


        if (empty($param['check_result'])) {
            return false;
        }
        $openId      = UserOauthModel::getMpWeiXinOpenId($param['user_id']);
        $wx_template = WxnoticeTemplate::wxMessageTemplate(['sale_service'])['sale_service'];//售后通知

        if ($wx_template['store_id'] == '10002') {//服装商城
            $formwork = '{
             "touser": "' . $openId . '",
             "template_id": "' . $wx_template['template_id'] . '",
             "page":"pages/refund/detail?orderRefundId=' . $param['order_refund_id'] . '",
             "data": {
                 "thing2": {
                     "value":"' . $goodName . '"
                 },
                "date5": {
                    "value": "' . date('Y-m-d H:i:s') . '"
                }
            }
        }';
        } else {
            $formwork = '{
             "touser": "' . $openId . '",
             "template_id": "' . $wx_template['template_id'] . '",
             "page":"pages/refund/detail?orderRefundId=' . $param['order_refund_id'] . '",
             "data": {
                 "thing1": {
                     "value":"' . $goodName . '"
                 },
                 "phrase2": {
                    "value": "' . $param['check_result'] . '"
                },
                "time3": {
                    "value": "' . date('Y-m-d H:i:s') . '"
                }
            }
        }';
        }

        $url    = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token . "";
        $result = helper::httpRequest($url, $formwork);
        log_record($result);
    }
    //虚拟商品充值失败、订单取消/订单缺货退款、售后退款通知
    public function WxMessageOrderRefund(array $param)
    {
        if(!isset($param['total_pay_price']) || empty($param['total_pay_price'])){
            //获取售后商品信息
            $model    = new OrderModel;
            $orderInfo = $model->where('order_id', '=', $param['order_id'])->find();
            $param['total_pay_price'] = $orderInfo['pay_price'];
        }
        $token = $this->getAccessToken();
        if (!$token) {
            throwError('微信配置有误');
        }
        if(isset($param['type']) && $param['type'] == RefundTypeEnum::RETURN){//退货退款售后订单
            $page = 'pages/refund/detail?orderRefundId=' . $param['order_refund_id'];
        }else{
            $page = 'pages/order/detail?orderId=' . $param['order_id'];
        }
        $openId      = UserOauthModel::getMpWeiXinOpenId($param['user_id']);
        $wx_template = WxnoticeTemplate::wxMessageTemplate(['refund'])['refund'];//售后通知
        if(!isset($param['remark']) && empty($param['remark'])){
            $param['remark'] = '已退款';
        }

        if ($wx_template['store_id'] == '10002') {//服装商城

        } else {
            $formwork = '{
             "touser": "' . $openId . '",
             "template_id": "' . $wx_template['template_id'] . '",
             "page":"' . $page . '",
             "data": {
                 "character_string1": {
                     "value":"' . $param['order_no'] . '"
                 },
                 "amount2": {
                    "value": "' . $param['total_pay_price'] . '"
                },
                "time3": {
                    "value": "' . date('Y-m-d H:i:s') . '"
                },
                "thing4": {
                    "value": "' . $param['refund_reason'] . '"
                },
                "thing5": {
                    "value": "' . $param['remark'] . '"
                }
            }
        }';
        }
        $url    = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token . "";
        $result = helper::httpRequest($url, $formwork);
        log_record($result);
    }
    //新品上线通知
    public function WxMessageGoodsNewArrival(array $param)
    {
        $SendMessageModel = new SendMessageModel();
        $list = $SendMessageModel->where('store_id', '=', $param['store_id'])
            ->where('times', '>', 0)
            ->where('type', '=', $param['type'])->select()->toArray();
        $goodsInfo = GoodsModel::detail($param['goodsId']);
        if(empty($list) || empty($goodsInfo) || $goodsInfo['good_type'] == 'virtual_good'){
            return true;
        }
        $token = $this->getAccessToken();
        if (!$token) {
            return true;
        }
        $goodName = helper::truncateString($goodsInfo['goods_name'], 20);
        $page = 'pages/goods/detail?goodsId=' . $goodsInfo['goods_id'];
        $wx_template = WxnoticeTemplate::wxMessageTemplate(['new_arrival'])['new_arrival'];//售后通知
        foreach ($list as $value){
            $formwork = '{
                     "touser": "' . $value['oauth_id'] . '",
                     "template_id": "' . $wx_template['template_id'] . '",
                     "page":"' . $page . '",
                     "data": {
                        "thing1": {
                            "value": "' . $goodName . '"
                        },
                        "amount2": {
                            "value": "' . $goodsInfo['goods_price_min'] . '"
                        },
                        "thing3": {
                            "value": "' . $param['reason'] . '"
                        }
                    }
                }';
            $url    = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token . "";
            $result = helper::httpRequest($url, $formwork);
            $response = $this->jsonDecode($result);
            $update['update_time'] = time();
            $update['send_result'] = $result;
            if($response['errcode'] == 0){
                $update['send_status'] = 1;
                $SendMessageModel->where(['user_id' => $value['user_id'], 'type' => $value['type']])->dec('times', 1)->update($update);
            }else if($response['errcode'] == 43101){
                $update['send_status'] = 2;
                $update['times'] = 0;
                $SendMessageModel->where(['user_id' => $value['user_id'], 'type' => $value['type']])->update($update);
            }else{
                $update['send_status'] = 2;
                $SendMessageModel->where(['user_id' => $value['user_id'], 'type' => $value['type']])->update($update);
            }
            log_record($result);
            sleep(1);
        }
    }
}
